﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace NaverAuthStmp
{
    public class VpsHelper
    {
        private volatile ArrayList ipList = ArrayList.Synchronized(new ArrayList());
        private static object _lock = new object();
        private static VpsHelper instance;
        public const int ChangeCount = 200;//切换IP重复次数

        private VpsHelper() { }

        public static VpsHelper GetInstance()
        {
            if (instance == null)
            {
                lock (_lock)
                {
                    if (instance == null)
                    {
                        instance = new VpsHelper();
                    }
                }
            }
            return instance;
        }

        public bool ChangeIp(string url)
        {
            var ip = string.Empty;
            for (var i = 0; i <= ChangeCount; i++)
            {
                ip = Get(url);
                if (JudgeIpIsUseed(ip))
                {
                    return true;
                }
            }

            return false;
        }

        private bool JudgeIpIsUseed(string ip)
        {
            if (ipList.Contains(ip))
            {
                return false;
            }
            lock (_lock)
            {
                if (!ipList.Contains(ip))
                {
                    ipList.Add(ip);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 发送Get请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="dic">请求参数定义</param>
        /// <returns></returns>
        private string Get(string url, Dictionary<string, string> dic = null)
        {
            string result = "";
            StringBuilder builder = new StringBuilder();
            builder.Append(url);
            if (dic != null && dic.Count > 0)
            {
                builder.Append("?");
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
            }
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
            //添加参数
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            try
            {
                //获取内容
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            finally
            {
                stream.Close();
            }
            return result;
        }
    }
}
